package com.lw.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

//@WebServlet("/uploadFile")
public class FileUploadServlet extends HttpServlet {
    private static final String UPLOAD_DIRECTORY = "uploads";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 检查请求是否是文件上传请求
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是，则停止
            PrintWriter writer = response.getWriter();
            writer.println("Error: 表单必须包含 enctype=multipart/form-data");
            writer.flush();
            return;
        }

        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            // 解析请求的内容提取文件数据
            List<FileItem> formItems = upload.parseRequest(request);

            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        String filePath = getServletContext().getRealPath("") +  UPLOAD_DIRECTORY + File.separator + fileName;
                        File storeFile = new File(filePath);

                        if(!storeFile.getParentFile().exists()){
                            storeFile.getParentFile().mkdirs();
                        }
                        if(!storeFile.exists()){
                            storeFile.createNewFile();
                        }


                        System.out.println(filePath);

                        // 保存文件到硬盘
                        item.write(storeFile);
                        request.setAttribute("message", "文件上传成功!");
                    }
                }
            }
        } catch (Exception ex) {
            log("",ex);
            request.setAttribute("message", "文件上传失败: " + ex.getMessage());
        }
        response.setStatus(200);
        response.setContentType("application/json");
        String json = """
                {"retMsg":"OK"}
                """;
        response.getOutputStream().write(json.getBytes());

        // 跳转到 message.jsp
//        getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
    }
}
